package monitor

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"strconv"
	"encoding/hex"
)

const (
	STRHELP = "help"
)

const (
	LOGTYPE_RECMSG = 1 << iota
	LOGTYPE_SEDMSG
	LOGTYPE_PG
	LOGTYPE_CMD
)

type Env struct {
	loglv int
	logsw int
}

var UserEnv Env

func cmdHelp () {
	fmt.Println("nstar_cmd 帮助:")
	fmt.Println("log -l x: 设置log等级")
	fmt.Println("log xxxx: 设置log输出类型，例如：1111 ->  指令，节目，输出，接收")
	
}

func cmdSet (cmd []string) {
	var s1, s2 string
	s1 = cmd[1]
	switch s1 {
	case "-l":
		if len(cmd) == 3 {
			s2 = cmd[2]
			i, err := strconv.Atoi(s2)
			if err == nil {
				UserEnv.loglv = i	
			}
		}
	//case "t":
	default:
		if len(cmd) ==2 {
			a, err := hex.DecodeString(s1)
			if err == nil && len(a) == 2{
				b0 := ((a[0]&0xf0) >> 4 )& 1
				b1 := ((a[0]&0xf) )& 1
				b2 := ((a[1]&0xf0) >> 4 )& 1
				b3 := ((a[1]&0xf) )& 1
				fmt.Println(b0, b1, b2, b3)
				UserEnv.logsw = int(int(b0)<< 3 + int(b1)<< 2 + int(b2)<< 1 + int(b3))
				fmt.Printf("type :%02x", UserEnv.logsw)
			}
		}
	}
	fmt.Println(UserEnv)
}
func echoHead () {
	fmt.Print("nstar_cmd:")
}


func RunEnv() {
	input := bufio.NewScanner(os.Stdin)
	echoHead()
	for input.Scan() {
		
		cmdstr := input.Text()
		cmd := strings.Split(cmdstr, " ")
		if(cmd[0]!= "") {
			switch cmd[0] {
				case "log":
					if len(cmd) < 2 {
						cmdHelp()
					}else {
						cmdSet(cmd)
					}
					continue
				case "help", "-h", "h":
					cmdHelp()	
			}
		}
		echoHead()
	}
}


func Idbg(lv int, a ...interface{}) {
	if lv <= UserEnv.loglv {
		fmt.Println(a...)
	}
}

func Idbghex(lv int, a []byte) {
	if lv <= UserEnv.loglv {
		fmt.Println(hex.Dump(a))
	}	
}

func IdbgRecv(lv int, a ...interface{}){
	if LOGTYPE_RECMSG&UserEnv.logsw != 0 {
		Idbg(lv, a...)
	}	
}

func IdbgRecvHex(lv int, a []byte) {
	if LOGTYPE_RECMSG&UserEnv.logsw != 0 {
		Idbghex(lv, a)
	}	
}

func IdbgSend(lv int, a ...interface{}){
	if LOGTYPE_SEDMSG&UserEnv.logsw != 0 {
		Idbg(lv, a...)
	}	
}

func IdbgSendHex(lv int, a []byte) {
	if LOGTYPE_SEDMSG&UserEnv.logsw != 0 {
		Idbghex(lv, a)
	}	
}

func IdbgCmd(lv int, a ...interface{}){
	if LOGTYPE_CMD&UserEnv.logsw != 0 {
		Idbg(lv, a...)
	}	
}

func IdbgCmdHex(lv int, a []byte) {
	if LOGTYPE_CMD&UserEnv.logsw != 0 {
		Idbghex(lv, a)
	}	
}


func IdbgPg(lv int, a ...interface{}){
	if LOGTYPE_PG&UserEnv.logsw != 0 {
		Idbg(lv, a...)
	}	
}

func IdbgPgHex(lv int, a []byte) {
	if LOGTYPE_PG&UserEnv.logsw != 0 {
		Idbghex(lv, a)
	}	
}


func init() {
	UserEnv.loglv = 0 
	UserEnv.logsw = 0

}

